package handler

import (
	"context"
	"go_final/mxshop_srvs/goods_srv/global"
	"go_final/mxshop_srvs/goods_srv/model"
	goodspb "go_final/mxshop_srvs/goods_srv/proto/protofile"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"

	"google.golang.org/protobuf/types/known/emptypb"
)

func (s Server) BannerList(c context.Context, empty *emptypb.Empty) (*goodspb.BannerListResponse, error) {
	var banners []*model.Banner
	res := global.DB.Find(&banners)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}

	var rsp = &goodspb.BannerListResponse{}
	rsp.Total = int32(res.RowsAffected)

	for _, banner := range banners {
		rsp.Data = append(rsp.Data, &goodspb.BannerResponse{
			Id:    banner.ID,
			Index: banner.Index,
			Image: banner.Image,
			Url:   banner.URL,
		})
	}

	return rsp, nil
}

func (s Server) CreateBanner(c context.Context, request *goodspb.BannerRequest) (*goodspb.BannerResponse, error) {
	var banner model.Banner
	res := global.DB.Where(model.Banner{
		URL: request.Url,
	}).First(&banner)

	if res.RowsAffected > 0 {
		return nil, status.Errorf(codes.AlreadyExists, "轮播图已存在, 添加轮播图失败")
	}

	banner.Image = request.Image
	banner.URL = request.Url
	banner.Index = request.Index

	res = global.DB.Create(&banner)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}

	return &goodspb.BannerResponse{
		Id:    banner.ID,
		Index: request.Index,
		Image: request.Image,
		Url:   request.Url,
	}, nil
}

func (s Server) DeleteBanner(c context.Context, request *goodspb.BannerRequest) (*emptypb.Empty, error) {
	res := global.DB.Delete(&model.Banner{}, request.Id)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected < 1 {
		return nil, status.Errorf(codes.NotFound, "没有该轮播图")
	}

	return &emptypb.Empty{}, nil
}

func (s Server) UpdateBanner(c context.Context, request *goodspb.BannerRequest) (*emptypb.Empty, error) {
	banner := &model.Banner{}
	banner.ID = request.Id

	if request.Image != "" {
		banner.Image = request.Image
	}

	if request.Url != "" {
		banner.URL = request.Url
	}
	banner.Index = request.Index

	res := global.DB.Updates(&banner)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected < 1 {
		return nil, status.Errorf(codes.NotFound, "没有该轮播图")
	}

	return &emptypb.Empty{}, nil
}
